package com.wzz.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbitmq.client.Channel;
import com.wzz.config.FreemarkerUtil;
import com.wzz.config.OSSFileUtil;
import com.wzz.mapper.GoodsMapper;
import com.wzz.mapper.ImgMapper;
import com.wzz.mapper.TextMapper;
import com.wzz.mapper.TypeMapper;
import com.wzz.pojo.Goods;
import com.wzz.pojo.Img;
import com.wzz.pojo.Text;
import com.wzz.pojo.Type;
import com.wzz.service.GoodsService;
import com.wzz.vo.MessageVo;
import com.wzz.vo.PageInfoVo;
import com.wzz.vo.R;
import freemarker.template.TemplateException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author DarkClown
 * @date 2024-08-12 10:39
 * @project_name day0812-month
 * @parem
 **/
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper,Goods> implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    ImgMapper imgMapper;

    @Autowired
    TextMapper textMapper;

    @Autowired
    TypeMapper typeMapper;

    @Override
    public R selectList(PageInfoVo pageInfoVo) {
        //分页
        Page<Goods> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        //排序
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().orderByAsc(Goods::getMyStatus).orderByDesc(Goods::getCreateTime);


        //列表

        Page<Goods> goodsPage = goodsMapper.selectGoods(page, queryWrapper);

        HashMap<String, Object> map = new HashMap<>();

        map.put("total",goodsPage.getTotal());
        map.put("records",goodsPage.getRecords());
        map.put("pageSize",pageInfoVo.getPageSize());
        map.put("pageNum",pageInfoVo.getPageNum());

        return R.OK(map);
    }

    @Override
    public R selectType(Integer id) {
        QueryWrapper<Type> queryWrapper = new QueryWrapper<>();

        LambdaQueryWrapper<Type> wrapper = queryWrapper.lambda().eq(Type::getPid, id);

        List<Type> types = typeMapper.selectList(wrapper);

        return R.OK(types);
    }

    @Override
    public R uploadFile(MultipartFile file) {
        OSSFileUtil ossFileUtil = new OSSFileUtil();
        try {
            String path = ossFileUtil.uploadFile(file);

            return R.OK("http://192.168.81.128:8888/"+path);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
//    @Transactional
    public R addGoods(Goods goods) {


//        String[] imgList = goods.getImgList();
//
//        for (String s : imgList) {
//            Img img = new Img();
//            img.setUrl(s);
//            img.setGid(goods.getGid());
//            imgMapper.insert(img);
//        }



        //编码为空
        if (StringUtils.isEmpty(goods.getGnum())){
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

            String format = simpleDateFormat.format(date);

            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();

            Long key = opsForValue.increment("key");

            goods.setGnum("JF"+format+key);


        }

        goods.setMyStatus(2);

        goods.setCreateTime(new Date());
        goodsMapper.insert(goods);
        //图片
        List<Img> imgList = goods.getImgList();
        for (Img img : imgList) {
            img.setGid(goods.getGid());
            imgMapper.insert(img);
        }
        //详情
        Text text = new Text();
        text.setText(goods.getText());
        text.setGid(goods.getGid());
        textMapper.insert(text);

        return R.OK();
    }

    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    private void innit(){
        //不丢失
        rabbitTemplate.setConfirmCallback(
                new RabbitTemplate.ConfirmCallback() {
                    @Override
                    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                        if (ack){
                            System.out.println("发送成功");
                        }
                        else {
                            System.out.println("发送失败");
                        }
                    }
                }
        );

        rabbitTemplate.setReturnCallback(
                new RabbitTemplate.ReturnCallback() {
                    @Override
                    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                        rabbitTemplate.convertAndSend(exchange,routingKey,message);
                    }
                }
        );

    }

    @Autowired
    HttpServletRequest request;


    @Override
    public R updateMyStatus(Goods goods, String token) {




        goodsMapper.updateById(goods);
        //上架
        if (goods.getMyStatus()==0){
            //获取uid
            Claims token1 = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
            Integer uid = token1.get("uid", Integer.class);

            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();

            //防止重复发送
            String ip = request.getRemoteAddr().toString();

            if (stringRedisTemplate.hasKey(ip+goods.getGid()+uid)){
                return R.ERROR(404,"不能重复发送");
            }


            opsForValue.set(ip+goods.getGid()+uid,"防止重复发送");


            goods.setUid(uid);

            MessageVo messageVo = new MessageVo();
            String uuid = UUID.randomUUID().toString();
            messageVo.setMsgId(uuid);
            messageVo.setMsgBody(JSON.toJSONString(goods));

            rabbitTemplate.convertAndSend("addEx","addKey",JSON.toJSONString(messageVo));
        }

        return R.OK("修改成功");
    }

    @Override
    public R selectId(Integer id) {
        Goods goods = goodsMapper.selectById(id);
        return R.OK(goods);

    }


    @RabbitListener(queues = "addQueue")
    public void addQueue(Message message, Channel channel){
        String s = new String(message.getBody());

        MessageVo messageVo = JSON.parseObject(s, MessageVo.class);

        Goods goods = JSON.parseObject(messageVo.getMsgBody(), Goods.class);

        Boolean aBoolean = stringRedisTemplate.hasKey(messageVo.getMsgId());


        HashMap<String, Object> map = new HashMap<>();
        map.put("goods",goods);
        String s3 = UUID.randomUUID().toString();
        String s2 = "C:\\Users\\Administrator\\Desktop\\template\\" + s3 + ".html";
        FreemarkerUtil freemarkerUtil = new FreemarkerUtil();
        try {
            String html = freemarkerUtil.createHtml(map, "goods", s2);

            OSSFileUtil ossFileUtil = new OSSFileUtil();
            FileInputStream fileInputStream = new FileInputStream(s2);
            String s1 = ossFileUtil.uploadHtml(fileInputStream, s3);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
            //消费完成删除
            String ip = request.getRemoteAddr().toString();
            String s4 = ip + goods.getGid() + goods.getUid();

            stringRedisTemplate.delete(s4);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }




    }
}
